import Vue from 'vue'
import Vuex from 'vuex'
import { setToken } from '../util/token'
import { getProfile } from '../api/user'
Vue.use(Vuex)

export default new Vuex.Store({
  state: {
    user: '',
    isLogin: false,
    // 保存token信息
    tokenInfo: {
      token: '',
      refresh_token: ''
    }
  },
  getters: {
    getInfo (state) {
      return state.user.getInfo
    }
  },
  mutations: {
    setUser (state, val) {
      state.user = val
    },
    setLogin (state, val) {
      state.isLogin = val
    },
    // 保存token到vuex
    SetTokenInfo (state, newToken) {
      state.tokenInfo = newToken
      setToken(JSON.stringify(state.tokenInfo))
    }
  },
  // 处理异步操作 传入context参数 通过commit方法传给mutations
  actions: {
    async getUser (context) {
      const res = await getProfile()
      // 得到数据 传给mutations中的函数 再由mutations赋值给state  调用
      context.commit('setUser', res.data.data)
    }
  },
  modules: {}
})
